//
//  NSString+TTString.m
//  TT
//
//  Created by 张福润 on 2017/2/27.
//  Copyright © 2017年 张福润. All rights reserved.
//

#import "NSString+TTString.h"
#import <CommonCrypto/CommonCrypto.h>
#import <UIKit/UIKit.h>
#import <AdSupport/ASIdentifierManager.h>
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@implementation NSString (TTString)

+ (BOOL)isNilOrEmpty:(NSString *)str {
    if (!str) {
        return YES;
    }
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (!temp || temp.length == 0) {
        return YES;
    }
    return NO;
}

- (NSString *)md5Str {
    const char *original_str = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (int)strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++) {
        [hash appendFormat:@"%02X", result[i]];
    };
    return [hash lowercaseString];
}

+ (NSString*)getMD5WithData:(NSData *)data{
    if (!data)
    {
        return nil;
        //判断sourceString如果为空则直接返回nil。
        
    }
    //需要MD5变量并且初始化
    CC_MD5_CTX md5; CC_MD5_Init(&md5);
    //开始加密(第一个参数：对md5变量去地址，要为该变量指向的内存空间计算好数据，第二个参数：需要计算的源数据，第三个参数：源数据的长度)
    CC_MD5_Update(&md5, data.bytes, (CC_LONG)data.length);
    //声明一个无符号的字符数组，用来盛放转换好的数据
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    //将数据放入result数组
    CC_MD5_Final(result, &md5);
    //将result中的字符拼接为OC语言中的字符串，以便我们使用。
    NSMutableString *resultString = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    {
        [resultString appendFormat:@"%02X",result[i]];
        
    }
    NSLog(@"resultString=========%@",resultString);
    return resultString;
        
        
       
    
}

+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key{
    NSString *ciphertext = nil;
    
    const char *textBytes = [plainText UTF8String];
    
    NSUInteger dataLength = [plainText length];
    
    
    unsigned char buffer[1024];
    
    memset(buffer, 0, sizeof(char));
    
    size_t numBytesEncrypted = 0;
    
    NSString *testString = key;
    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
    Byte *iv = (Byte *)[testData bytes];
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          
                                          kCCOptionECBMode|kCCOptionPKCS7Padding,  //kCCOptionECBMode  kCCOptionPKCS7Padding
                                          
                                          [key UTF8String], kCCKeySizeDES,
                                          
                                          iv,
                                          
                                          textBytes, dataLength,
                                          
                                          buffer, 1024,
                                          
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        
        
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        ciphertext = [self base64Encoding:data];
  
    }
    
    return ciphertext;
}



+(NSString *)base64Encoding:(NSData*) text
{
    if (text.length == 0)
        return @"";
    
    char *characters = malloc(text.length*3/2);
    
    if (characters == NULL)
        return @"";
    
    int end = (int)text.length - 3;
    int index = 0;
    int charCount = 0;
    int n = 0;
    
    while (index <= end) {
        int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)
        | (((int)(((char *)[text bytes])[index + 1]) & 0x0ff) << 8)
        | ((int)(((char *)[text bytes])[index + 2]) & 0x0ff);
        
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = encodingTable[(d >> 6) & 63];
        characters[charCount++] = encodingTable[d & 63];
        
        index += 3;
        
        if (n++ >= 14)
        {
            n = 0;
            characters[charCount++] = ' ';
        }
    }
    
    if (index == text.length - 2)
    {
        int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)
        | (((int)(((char *)[text bytes])[index + 1]) & 255) << 8);
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = encodingTable[(d >> 6) & 63];
        characters[charCount++] = '=';
    }
    else if (index == text.length - 1)
    {
        int d = ((int)(((char *)[text bytes])[index]) & 0x0ff) << 16;
        characters[charCount++] = encodingTable[(d >> 18) & 63];
        characters[charCount++] = encodingTable[(d >> 12) & 63];
        characters[charCount++] = '=';
        characters[charCount++] = '=';
    }
    NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
    return rtnStr;
}

/**
 在2013年3月21日苹果已经通知开发者，从2013年5月1日起，访问UIDID的应用将不再能通过审核，替代的方案是开发者应该使用“在iOS 6中介绍的Vendor或Advertising标示符”。
 分散式系統中的所有元素，都能有唯一的辨识资讯，而不需要透过中央控制端來做辨识资讯的指定。如此一來，每個人都可以建立不与其它人冲突的 UUID。在這样的情況下，就不需考虑资料库建立时的名称重复问题
 UUID OR GUID最大优点在於算法不依赖数据库，可以入库前预生成。
 */
+ (NSString *)GUIDString {
    return [self UUIDString];
}

+ (NSString *)NSUUIDString {
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return uuid;
}

/**
 一个Vendor是CFBundleIdentifier（反转DNS格式）的前两部分
 */
+ (NSString *)vendorString {
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return idfv;
}

/**
 UDID的全名为 Unique Device Identifier :设备唯一标识符
 UDID是一个40位十六进制序列
 在iOS5 中可以获取,但是,在此之后,被苹果禁用了
 + (NSString *)UDIDString {
 NSString *udid = [[UIDevice currentDevice] uniqueIdentifier];
 return udid;
 }
 */

+ (NSString *)UUIDString {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

+ (NSString *)IDFAString {
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adId;
}

@end
